package com.tiance.demo.ui.ability;

import javafx.event.EventHandler;
import javafx.scene.ImageCursor;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;

public class Draggable implements EventHandler<MouseEvent> {

    /**
     * 拉左边
     */
    public static final int DRAG_LEFT = 1;
    /**
     * 拉右边
     */
    public static final int DRAG_RIGHT = 2;

    /**
     * 开始拉的标识位
     */
    protected volatile boolean dragged = false;

    /**
     * 组件的边, 如左边, 右边
     */
    private int borderToDrag;

    public Draggable(int borderToDrag) {
        this.borderToDrag = borderToDrag;
    }

    /**
     * 鼠标拖拽的实现
     *
     * @param event
     */
    @Override
    public void handle(MouseEvent event) {
        Pane pane = (Pane) event.getSource();

        if (event.getEventType() == MouseEvent.DRAG_DETECTED) {
            pane.startFullDrag();
            if (borderToDrag == DRAG_RIGHT && Math.abs(event.getX() - pane.getWidth()) < 20) {
                dragged = true;
            } else if (borderToDrag == DRAG_LEFT && Math.abs(event.getX()) < 20) {
                dragged = true;
            }
        } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
            if (dragged) {
                pane.getScene().setCursor(ImageCursor.W_RESIZE);
                if (borderToDrag == DRAG_LEFT) {
                    pane.setPrefWidth(pane.getScene().getWidth() - event.getSceneX());
                } else if (borderToDrag == DRAG_RIGHT) {
                    pane.setPrefWidth(event.getSceneX());
                }
            }
        } else if (event.getEventType() == MouseDragEvent.MOUSE_DRAG_RELEASED
                || event.getEventType() == MouseEvent.MOUSE_RELEASED) {
            dragged = false;
            pane.getScene().setCursor(ImageCursor.DEFAULT);
        }
    }


}
